package com.example.mobile2021606163crw0516;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.mobile2021606163crw0516.fragment.BulletinsFragment;
import com.example.mobile2021606163crw0516.fragment.NewsFragment;
import com.example.mobile2021606163crw0516.fragment.NoticesFragment;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager2 viewPager2;
    List<Fragment> fragmentList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        fragmentList.add(NewsFragment.newInstance("新闻",""));
        fragmentList.add(NoticesFragment.newInstance("通知",""));
        fragmentList.add(BulletinsFragment.newInstance("公告",""));
        //创建适配器对象，并设置给viewpager2
        ViewPageAdapter adapter = new ViewPageAdapter(getSupportFragmentManager(),getLifecycle(),fragmentList);
        viewPager2.setAdapter(adapter);
        //将view pager2跟Tablayout联系起来
        new TabLayoutMediator(tabLayout, viewPager2, true, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(fragmentList.get(position).getArguments().getString("title"));
            }
        }).attach();
    }

    private void initView() {
        tabLayout = (TabLayout) findViewById(R.id.TabLayout);
        viewPager2 = (ViewPager2) findViewById(R.id.ViewPager2);
    }
}